package com.snopy.concurrency.pool;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author snopy
 * @version 1.0.0
 * @classname DemoForkJoin
 * @description
 *
 * Fork/Join
 * 基于分治思想，加入多线程，适用于可采分的任务
 * @email 77912204@qq.com
 * @date 2022/06/29 14:37
 */
@Slf4j
public class DemoForkJoin {

    static Integer result = 0;
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool(12);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            result = pool.invoke(new MyTask(1000));
        }
        long end = System.currentTimeMillis();
        log.info("{},cost:{}ms",result,end-start);
        start = System.currentTimeMillis();
        for (int k = 0; k < 10000; k++) {
            result = 0;
            for (int i = 0; i < 1000; i++) {
                result+=i;
            }
        }
        end = System.currentTimeMillis();
        log.info("{},cost:{}ms",result,end-start);
    }
}

class MyTask extends RecursiveTask<Integer> {
    private int n;

    public MyTask(int n) {
        this.n = n;
    }

    /**
     * The main computation performed by this task.
     *
     * @return the result of the computation
     */
    @Override
    protected Integer compute() {
        if (n==1){
            return 1;
        }
        MyTask t1 = new MyTask(n-1);
        t1.fork();
        Integer reuslt = n + t1.join();
        return reuslt;
    }
}